﻿var vm = new Vue({
    el: '#app'
    , data: {
        search: {
            upid: 0
            , ordername: ''
            , ordertype: null
            , page: 1
            , keywords: ''
        }
        , loading: true //是否显示加载条
        , records: []
        , searchType: 1 //1 所有文件  99 垃圾筒
        , menus: []
        , uploadList: []
        , checkAllStatus: false
        , itemHasCheck: false
        , disabledScroll: false
        , existsFiles: []
        , selected: {
            status: false
            , record: {}
            , loading: false
            , logs: []
        }
        , showDefineFrame: false // 显示自定义还原的文件列表
        , restoreVisible: false // 还原规则窗口选择
        , restoreCheckAll: false
        , positionCheckAll: false
        , isContinueSameRestore: false //是否后续所有文件都按所选择的方法进行还原
        , currentDateTime: null
        , restoringInfo: {
            ids: [], // 要还原的记录所在的ID
            selectedType: null,//选择的处理冲突方法
            index: -1//还原的文件索引-就是选择的要的还原的文件中正在被还原的文件或文件夹所在索引
        }
        , editid: -2 //-2表示没有选择到要编辑的记录
        , restoreCheckAllChangeTrigger: ''
        , dragInfo: {
            dragObj: null
            , targetObj: null
        }
    }
    , mounted: function () {
        let me = this;
        this.initDragFiles();//初始化拖动上传功能
        setInterval(function () {
            me.currentDateTime = new Date();
        }, 1000);
        me.currentDateTime = new Date();
    }
    , watch: {
        currentDateTime: function (newVal, oldVal) {
            let me = this;
            this.records.forEach(function (x) {
                if (me.searchType == 1) {
                    me.$set(x, 'edit_date_diff', me.formatDateTime(x.edit_date));
                }
                else {
                    me.$set(x, 'edit_date_diff', me.formatDateTime(x.delete_date));
                }
            });
            //if (this.selected.status) {
            //    this.selected.logs.forEach(function (x) {
            //        me.$set(x, 'op_date_diff', me.formatDateTime(x.op_date));
            //    });
            //}
        }
        , checkAllStatus: function (newVal, oldVal) {
            if (this.checkAllStatusChangeTrigger == 'click') {
                this.checkAllStatusChangeTrigger = '';
                let me = this;
                this.records.forEach(function (x) {
                    me.$set(x, 'check', newVal);
                });
                this.handleItemChange();
            }
        }
        , restoreCheckAll: function (newVal, oldVal) {
            if (this.restoreCheckAllChangeTrigger == 'click') {
                this.restoreCheckAllChangeTrigger = '';
                this.existsFiles.forEach(function (x) {
                    x.restoreCheck = newVal;
                });
            }
        }
        , positionCheckAll: function (newVal, oldVal) {
            if (this.positionCheckAllChangeTrigger == 'click') {
                this.positionCheckAllChangeTrigger = '';
                this.existsFiles.forEach(function (x) {
                    x.positionCheck = newVal;
                });
            }
        }
    }
    , computed: {
        dateTitleString: function () {
            let str = '';
            switch (this.searchType) {
                case 1:
                    str = '上传/修改时间';
                    break;
                case 99:
                    str = '删除时间';
                    break;
                default:
                    break;
            }
            return str;
        }
    }
    , methods: {
        load: function () {
            this.onQuery();
        }
        , getQueryUrl: function () {
            let url;
            switch (this.searchType) {
                case 1:
                    url = '/show/List'
                    break;
                case 99:
                    url = '/show/ListDeleted'
                    break;
                default:
                    break;
            }
            return url;
        }
        , onQuery: hcCore.debounce(function () {
            vm.loading = true;
            hcCore.post({
                url: vm.getQueryUrl()
                , loading: false
                , param: {
                    pid: vm.search.upid
                    , name: vm.search.keywords
                    , ordername: vm.search.ordername
                    , ordertype: vm.search.ordertype
                    , page: vm.search.page
                }
                , success: function (rsp) {
                    vm.disabledScroll = !(rsp.data && rsp.data.length > 0);
                    rsp.data.forEach(p => {
                        vm.$set(p, 'check', false);
                    });
                    if (rsp.data.length > 0) {
                        vm.records = vm.records.concat(rsp.data);
                        vm.search.page++;
                    }
                    vm.handleItemChange();
                }
                , complete: function () {
                    vm.loading = false;
                }
            });
        }, 100)
        , onFilter: hcCore.debounce(function () {
            vm.search.page = 1;
            hcCore.post({
                url: vm.getQueryUrl()
                , loading: false
                , param: {
                    pid: vm.search.upid
                    , name: vm.search.keywords
                    , ordername: vm.search.ordername
                    , ordertype: vm.search.ordertype
                    , page: vm.search.page
                }
                , success: function (rsp) {
                    vm.records = [];
                    if (rsp.data && rsp.data.length > 0) {
                        rsp.data.forEach(p => {
                            vm.$set(p, 'check', false);
                        });
                        vm.records = rsp.data;
                    }
                    else {
                        vm.disabledScroll = true;
                        vm.search.page++;
                    }
                    vm.handleItemChange();
                }
            });
        }, 1000)
        , showRoot: function () {
            this.search.page = 1;
            this.search.upid = 0;
            this.menus = [];
            this.records = [];
            this.selected.status = false;
            this.onQuery();
        }
        , showUpFiles: function (id) {
            this.search.page = 1;
            let index = this.menus.findIndex(p => p.value == id);
            if (index > -1 && index < this.menus.length - 1) {
                this.menus.splice(index + 1, this.menus.length - index);
            }
            this.search.upid = id;
            this.records = [];
            this.selected.status = false;
            this.onQuery();
        }
        , showFiles: function (item) {
            this.search.page = 1;
            this.search.upid = item.id;
            this.menus.push({
                name: item.name
                , value: item.id
            });
            this.records = [];
            this.selected.status = false;
            this.onQuery();
        }
        , showLogs: function () {
            let me = this;
            this.selected.loading = true;
            //this.selected.logs = [];
            setTimeout(function () {
                hcCore.post({
                    url: '/show/ListFileLogs'
                    , loading: false
                    , param: {
                        id: me.selected.record.id
                    }
                    , success: function (rsp) {
                        me.selected.logs = rsp.data;
                    }
                    , complete: function () {
                        me.selected.loading = false;
                    }
                });
            }, 10);
        }
        , showSearchType: function (type) {
            this.searchType = type;
            this.showRoot();
        }
        , selectedItem: function (item) {
            this.selected.status = true;
            this.selected.record = item;
            this.showLogs();
        }
        , closeDetails: function () {
            this.selected.status = false;
        }
        , handleNewCmd: function (command) {
            switch (command) {
                case 'folder':
                    this.showInsertRecord();
                    break;
                case 'upload':
                    this.showUpload();
                    break;
                default:
                    break;
            }
        }
        , handleOpCmd: function (command) {
            let arr = command.split('-');
            let cmd = arr[0];
            let id = arr[1];
            switch (cmd) {
                case 'rename':
                    this.rename(id);
                    break;
                case 'delete':
                    this.delete(id);
                    break;
                case 'download':
                    this.download(id);
                    break;
                case 'restore':
                    this.startRestore(id);
                    break;
                default:
                    break;
            }
        }
        , handleCheckAllStatus: function () {
            this.checkAllStatusChangeTrigger = 'click';
        }
        , handleItemChange: function (newValue) {
            this.itemHasCheck = this.records.findIndex(p => p.check == true) > -1;
            let itemCount = this.records.length;
            let checkedCount = this.records.filter(p => p.check == true).length;
            this.checkAllStatus = itemCount == 0 ? false : (itemCount <= checkedCount);
        }
        , handleBatchDelete: function () {
            let ids = this.records.filter(p => p.check == true).map(p => p.id);
            this.delete(ids.join(','));
        }
        , handleBatchRestore: function () {
            let ids = this.records.filter(p => p.check == true).map(p => p.id);
            this.startRestore(ids.join(','));
        }
        , showInsertRecord: function () {
            this.createFolder({
                upid: this.search.upid
                , name: '新增文件夹'
            });
        }
        , formatDateTime: function (time) {
            return hcCore.getDateDiff(time);
        }
        , createFolder: function (item) {
            let me = this;
            console.log({
                api: 'CreateFolder'
                , upid: item.upid
            });
            hcCore.post({
                url: '/show/CreateFolder'
                , param: {
                    upid: item.upid
                    , name: item.name
                    , rnd: new Date().getTime()
                }
                , success: function (rsp) {
                    me.editid = rsp.data.id;
                    me.records.unshift(rsp.data);
                }
            });
        }
        , updateName: function (item) {
            let me = this;
            hcCore.post({
                url: '/show/Rename'
                , param: {
                    id: item.id
                    , name: item.name
                    , rnd: new Date().getTime()
                }
                , success: function (rsp) {
                    hcCore.showSuccess('提交成功');
                    me.editid = -2;
                    let index = me.records.findIndex(function (x) { return x.id == item.id });
                    me.records[index].edit_date = rsp.data.edit_date;
                    //如果文件/文件夹状态信息已展开，则要重新加载状态信息
                    if (me.selected.status) {
                        me.showLogs();
                    }
                }
            });
        }
        , unfocus: function (e) {
            e.target.blur();
        }
        , renderSize: function (size) {
            let result = 0;
            let unit = 'Byte';
            if (size < 1024) {
                result = size;
            }
            else if (size < 1024 * 1024) {
                result = (size / 1024).toFixed(2);
                unit = 'KB'
            }
            else if (size < 1024 * 1024 * 1024) {
                result = (size / 1024 / 1024).toFixed(2);
                unit = 'MB';
            }
            else if (size < 1024 * 1024 * 1024 * 1024) {
                result = (size / 1024 / 1024 / 1024).toFixed(2);
                unit = 'GB';
            }
            else {
                result = (size / 1024 / 1024 / 1024 / 1024).toFixed(2);
                unit = 'TB';
            }
            return result + ' ' + unit;
        }
        , showUpload: function () {
            document.getElementById('fileObj').click();
        }
        , rename: function (id) {
            this.editid = id;
        }
        , delete: function (ids) {
            let me = this;
            hcCore.confirm('确定要删除所选记录吗？', function () {
                hcCore.post({
                    url: '/show/Delete'
                    , param: { ids: ids }
                    , success: function (rsp) {
                        let idArr = ids.split(',');
                        for (let i = 0; i < idArr.length; i++) {
                            let index = me.records.findIndex(function (x) {
                                return x.id == idArr[i]
                            });
                            if (index > -1) {
                                me.records.splice(index, 1);
                            }
                        }
                        me.handleItemChange();
                    }
                });
            });
        }
        , upload: function (event, uploadFiles) {
            let me = this;
            let files = uploadFiles || event.target.files;
            if (files && files.length > 0) {
                for (let i = 0; i < files.length; i++) {
                    let fileName = '[' + files[i].name + ']';
                    let formData = new FormData();
                    formData.append('filelist[]', files[i]);
                    formData.append('pid', this.search.upid);
                    formData.append('rnd', new Date().getTime());
                    let reader = null;
                    let fileRecord = {
                        id: fileName + '-.' + i + '-' + 1
                        , filename: fileName
                        , percentage: 0
                    };
                    if (FileReader) {
                        reader = new FileReader();
                        reader.readAsText(files[i]);
                        let maxSize = files[i].size;
                        reader.onprogress = function (evt) {
                            fileRecord.percentage = parseInt(evt.loaded / maxSize * 100);
                            if (fileRecord.percentage >= 100) {
                                fileRecord.percentage = 99;
                            }
                        };
                    }
                    me.uploadList.push(fileRecord);
                    $.ajax({
                        url: hcCore.virtualDirectory + '/show/Upload'
                        , method: 'post'
                        , data: formData
                        , processData: false
                        , contentType: false
                        , success: function (rsp) {
                            if (rsp && rsp.success) {
                                hcCore.showSuccess(fileName + ':上传成功');
                                me.records.unshift(rsp.data);
                            }
                            else {
                                hcCore.showError(fileName + ':' + (rsp && rsp.message || '上传失败'));
                            }
                            let index = me.uploadList.findIndex(function (x) { return x.id == fileRecord.id; });
                            if (index > -1) {
                                me.uploadList.splice(index, 1);
                            }
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            hcCore.showError(fileName + ':上传失败（' + textStatus + '） > （' + (errorThrown || '服务器未返回结果') + '）');

                            let index = me.uploadList.findIndex(function (x) { return x.id == fileRecord.id; });
                            if (index > -1) {
                                me.uploadList.splice(index, 1);
                            }

                        }
                    });
                }
            }

            document.getElementById('fileObj').value = '';
        }
        , download: function (id) {
            hcCore.handleExport('/show/download?id=' + id);
        }
        , existsRestore: function (ids) {

        }
        , startRestore: function (ids) {
            let idArr = ids.split(',');
            this.restoringInfo.ids = idArr;
            this.restoringInfo.index = 0;
            this.judgeExistRepeatFiles();
        }
        , judgeExistRepeatFiles: function () {
            let me = this;
            me.showDefineFrame = false;
            me.existsFiles = [];
            hcCore.post({
                url: '/show/ExistRepeatFiles'
                , param: {
                    id: me.restoringInfo.ids[me.restoringInfo.index]
                }
                , success: function (rsp) {
                    if (rsp.data.length > 0) {
                        me.existsFiles = rsp.data;
                        for (let i = 0; i < me.existsFiles.length; i++) {
                            me.$set(me.existsFiles[i], "restoreCheck", false);
                            me.$set(me.existsFiles[i], "positionCheck", false);
                        }
                        //如果前面已勾选【后续所有文件都按所选择的方法进行还原】，且选择的不是【自定义每个文件的还原原则】
                        //则自动进行还原，否则，弹出选择对话框
                        if (me.isContinueSameRestore && me.restoringInfo.selectedType && me.restoringInfo.selectedType != 4) {
                            setTimeout(function () {
                                me.restoreVisible = false;
                                me.restore(me.restoringInfo.selectedType);
                            }, 10);
                        }
                        else {
                            me.restoreVisible = true;
                        }
                    }
                    else {
                        //没有冲突文件，直接还原
                        setTimeout(function () {
                            me.restore(0);
                        }, 10);
                    }
                }
            });
        }
        , restore: function (type) {
            let me = this;
            me.restoringInfo.selectedType = type;
            let selfRestores = [];
            if (me.existsFiles && me.existsFiles.length > 0) {
                for (let i = 0; i < me.existsFiles.length; i++) {
                    let value = me.existsFiles[i].restoreCheck && me.existsFiles[i].positionCheck ?
                        3 : me.existsFiles[i].restoreCheck ?
                            2 : me.existsFiles[i].positionCheck ?
                                1 : 0;
                    selfRestores.push({
                        Key: me.existsFiles[i].Key
                        , Value: value
                    });
                }
            }
            hcCore.post({
                url: '/show/Restore'
                , param: {
                    ids: me.restoringInfo.ids[me.restoringInfo.index]
                    , dealType: type
                    , selfRestores: JSON.stringify(selfRestores)
                }
                , success: function (rsp) {
                    //还原成功后，如果顶级文件/文件夹记录选择的是跳过，则不用删除当前记录
                    let isDeleteRow = true;
                    if (type == 1) {
                        isDeleteRow = false;
                    }
                    else if (type == 4) {
                        let tempRecord = selfRestores.find(function (x) {
                            return x.Key == me.restoringInfo.ids[me.restoringInfo.index]
                        });
                        if (tempRecord != null && tempRecord.Value == 1) {
                            isDeleteRow = false;
                        }
                    }
                    if (isDeleteRow) {
                        let index = me.records.findIndex(function (x) {
                            return x.id == me.restoringInfo.ids[me.restoringInfo.index]
                        });
                        if (index > -1) {
                            me.records.splice(index, 1);
                        }
                        me.handleItemChange();
                    }

                    //继续还原下一个文件/文件夹
                    me.restoringInfo.index++;
                    me.restoreVisible = false;
                    if (me.restoringInfo.index > -1 && me.restoringInfo.index < me.restoringInfo.ids.length) {
                        me.existsFiles = [];
                        setTimeout(function () {
                            me.judgeExistRepeatFiles();
                        }, 10);
                    }
                    else {
                        me.restoringInfo.index = -1;
                        me.restoringInfo.ids = [];
                        me.restoringInfo.selectedType = null;
                        me.isContinueSameRestore = false;
                    }
                }
            });
        }
        , handleBatchDownload: function () {
            let ids = this.records.filter(p => p.check == true).map(p => p.id);
            hcCore.handleExport('/show/downloads?ids=' + ids.join(','));
        }
        , filesDrop: function (e) {
            e.stopPropagation();
            e.preventDefault();
            if (this.searchType == 1) {
                let fileData = e.dataTransfer.files;
                this.upload(null, fileData);
            }
        }
        , initDragFiles: function () {
            let dropbox = document.getElementById('fileList');
            dropbox.addEventListener("drop", this.filesDrop, false)
            dropbox.addEventListener("dragleave", function (e) {
                e.stopPropagation();
                e.preventDefault();
            })
            dropbox.addEventListener("dragenter", function (e) {
                e.stopPropagation();
                e.preventDefault();
            })
            dropbox.addEventListener("dragover", function (e) {
                e.stopPropagation();
                e.preventDefault();
            })
        }
        , judgeTypeClass: function (name, type) {
            //return this.ordername == name && this.ordertype == type;
            if (this.search.ordername == name) {
                if (this.search.ordertype == 0) {
                    return 'el-icon-caret-top';
                }
                else if (this.search.ordertype == 1) {
                    return 'el-icon-caret-bottom';
                }
            }
            return 'el-icon-d-caret';
        }
        , changeOrderByInfo: function (ordername) {
            if (this.search.ordername == ordername) {
                if (this.search.ordertype === 0) {
                    this.search.ordertype = 1;
                }
                else if (this.search.ordertype === 1) {
                    this.search.ordertype = null
                }
                else {
                    this.search.ordertype = 0;
                }
            }
            else {
                this.search.ordername = ordername;
                if (this.search.ordertype === null) {
                    this.search.ordertype = 0;
                }
            }
            this.records = [];
            this.search.page = 1;
            this.onQuery();
        }
        , handleRestoreCheck: function () {
            let count = this.existsFiles.length;
            let checkedCount = this.existsFiles.filter(function (x) { return x.restoreCheck; }).length;
            this.restoreCheckAll = count > 0 && checkedCount >= count;
        }
        , handleRestoreCheckAll: function () {
            this.restoreCheckAllChangeTrigger = 'click';
        }
        , handlePositionCheck: function () {
            let count = this.existsFiles.length;
            let checkedCount = this.existsFiles.filter(function (x) { return x.positionCheck; }).length;
            this.positionCheckAll = count > 0 && checkedCount >= count;
        }
        , handlePositionCheckAll: function () {
            this.positionCheckAllChangeTrigger = 'click';
        }
        /********* 拖动定义 start ***********/
        , dragstart: function (item) {
            this.dragInfo.dragObj = item;
        }
        , dragenter: function (e, item) {
            e.preventDefault();
        }
        , dragover(e, item) {
            e.preventDefault();
            if (item.type == 1) {
                this.dragInfo.targetObj = item;
                this.$set(item, 'dragOver', true);
            }
        }
        , dragleave: function () {
            this.dragInfo.targetObj = null;
        }
        , dragend: async function (item) {
            let me = this;
            if (this.dragInfo && this.dragInfo.targetObj && this.dragInfo.targetObj.type == 1 && this.dragInfo.targetObj.id != item.id && this.dragInfo.targetObj.id != item.upid) {
                await hcCore.post({
                    url: '/show/Move'
                    , param: {
                        moveId: item.id
                        , targetId: this.dragInfo.targetObj.id
                    }
                    , success: function (rsp) {
                        let removeIndex = me.records.findIndex(function (x) { return x.id == item.id });
                        if (removeIndex > -1) {
                            me.records.splice(removeIndex, 1);
                        }
                        if (typeof me.dragInfo.targetObj.size == 'number') {
                            me.dragInfo.targetObj.size = rsp.data.size;
                            me.dragInfo.targetObj.edit_date = rsp.data.edit_date;
                            me.dragInfo.targetObj.edit_date_diff = me.formatDateTime(rsp.data.edit_date);
                        }
                    }
                });
            }
            this.dragInfo.targetObj = {};
        }
        /********* 拖动定义 end ***********/
    }
});